﻿

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using StockTraderRI.Infrastructure.Interfaces;
using StockTraderRI.Infrastructure.Models;
using StockTraderRI.Modules.Market.Properties;

namespace StockTraderRI.Modules.Market.Services
{
    /// <summary>
    /// 从文件了得所有股票数据，接口返回一个股票的数据
    /// </summary>
    public class MarketHistoryService : IMarketHistoryService
    {
        private Dictionary<string, MarketHistoryCollection> _marketHistory;

        public MarketHistoryService()
        {
            InitializeMarketHistory();
        }
        /// <summary>
        /// 从XML文件读入股票数据，保存在_marketHistory
        /// </summary>
        private void InitializeMarketHistory()
        {
            XDocument document = XDocument.Parse(Resources.MarketHistory);

            _marketHistory = document.Descendants("MarketHistoryItem")
                .GroupBy(x => x.Attribute("TickerSymbol").Value,
                         x => new MarketHistoryItem
                         {
                             DateTimeMarker = DateTime.Parse(x.Attribute("Date").Value, CultureInfo.InvariantCulture),
                             Value = Decimal.Parse(x.Value, NumberStyles.Float, CultureInfo.InvariantCulture)
                         })
                .ToDictionary(group => group.Key, group => new MarketHistoryCollection(group));
        }
        /// <summary>
        /// 从字典中返回一个股票的数据
        /// </summary>
        /// <param name="tickerSymbol"></param>
        /// <returns></returns>
        public MarketHistoryCollection GetPriceHistory(string tickerSymbol)
        {
            MarketHistoryCollection items = _marketHistory[tickerSymbol];
            return items;
        }
    }
}
